import { createRouter, createWebHashHistory } from 'vue-router'
import { localCache } from '@/utils/cahe'
import { firstMenu } from '@/utils/map-menus'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/main'
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('../views/main/main.vue')
    },
    {
      path: '/login',
      component: () => import('../views/login/login.vue')
    },
    {
      path: '/:pathMath(.*)',
      component: () => import('../views/not-found/notFound.vue')
    }
  ]
})

// 导航守卫

router.beforeEach((to, from) => {
  // 只有登入成功（含有token）才能进入到 mian，否则进入 login
  const token = localCache.getCache('token')
  // 如果是 跳转到mian 并且 token 没有值的情况下
  if (to.path === '/main' && !token) return '/login'

  // 路由拦截
  // 如果是进入到 main 页面，统一跳转到 设定的第一个路由
  if (to.path === '/main') return firstMenu?.url
})
export default router
